package com.fingard.dsp.tcpserver;

import java.util.concurrent.atomic.AtomicInteger;

import com.fingard.FGBiz;

public class BankResetEvent {

	//private int reqCount;//NIO 单线程，不需定义为AtomicInteger
	private Object mutexObj;
	public BankResetEvent(){
		init(5000);
	}
	
	public BankResetEvent(long pTimeout){
		init(pTimeout);
	}
	
	private void init(long pTimeout){
		mutexObj = new Object();
		blockFlag = new AtomicInteger();
		timeout = pTimeout;
	}
	
	/**1表示阻塞，0表示非阻塞*/
	private AtomicInteger blockFlag;
	
	private long timeout;
	public void setTimeout(long pTimeout){
		timeout = pTimeout;
	}
	
	/**阻塞*/
	public void waitOne(){
		//如果队列有新进，则不阻塞
		//blockFlag由0变为1，则进行阻塞
			try {
				synchronized(mutexObj){
					blockFlag.set(1);
					//System.out.println("wait");
					mutexObj.wait(timeout);//最多timeout毫秒
					blockFlag.set(0);
				}
			} catch (InterruptedException e) {
				FGBiz.limitMsg.exception("BankResetEvent.waitOne", e);
			}catch(Exception ex){
				FGBiz.limitMsg.exception("BankResetEvent.waitOne", ex);
			}
		
	}
	
	/**取消阻塞，继续运行*/
	public void set(){
		if(blockFlag.compareAndSet(1, 0)){
			try {
				synchronized(mutexObj){
					//System.out.println("notifyAll");
					mutexObj.notifyAll();
				}
			} catch (Exception e) {
				FGBiz.limitMsg.exception("BankResetEvent.set", e);
			}
		}
	}
}
